package com.idrem.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

public class HttpHelper {

	private static String TAG = "Http Helper: ";

	private static final String CHARSET = HTTP.UTF_8;

	private static HttpClient customerHttpClient;

	/**
	 * Constructor.
	 */
	private HttpHelper() {
	}

	/**
	 * Get a http host object.
	 */
	public static HttpHost getHttpHost() {
		return new HttpHost("www.google.com.hk", 443, "https");
	}

	public static String postXML(HashMap<String, String> paramValue, String url) {
		HttpClient client = new DefaultHttpClient();
		StringBuffer sb = new StringBuffer("");
		HttpPost post = new HttpPost(url);
		
		post.addHeader("Content-Type", "text/xml");
		try {
			List params = new ArrayList();
			for (String key : paramValue.keySet()) {
			
				params.add(new BasicNameValuePair(key, paramValue.get(key))); // 添加必须的参数
			}
			
			// 发出HTTP request
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			
			HttpResponse response = client.execute(post);
			int statuscode = response.getStatusLine().getStatusCode();

			if (statuscode == 200) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent()));

				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}
				in.close();

			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return sb.toString();
	}

	

	private Object getSoapData(HashMap<String, String> paramValue, String url) {

		String wsdlURL;
		String webMethod;
		String namespace;
		String soapAction;
		SoapObject soapObject;
		SoapSerializationEnvelope envelope;
		HttpTransportSE se;

		// 步骤1：设置WebService的调用参数 namespace是包名的反转
		wsdlURL = "http://172.31.147.20:8080/CloudService/services/Calculate";
		webMethod = "add";
		namespace = "http://service.chinasoft.com";
		soapAction = namespace + webMethod;

		// 步骤2：创建一个对象SoapObject 信封中的信内容
		soapObject = new SoapObject(namespace, webMethod);
		// 步骤3：传递参数
		// soapObject.addProperty("num1",num1);
		// soapObject.addProperty("num2",num2);

		// 步骤4：创建一个SoapSerializationEnvelope，信封：设定信封传递方式
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		// 步骤5：设置一下传回对象 将信装载到信封
		envelope.bodyOut = soapObject;

		// 步骤6：创建HttpTransportSE,用于传输数据，邮递员：将邮递地址给予邮递员
		se = new HttpTransportSE(wsdlURL);
		try {
			// 步骤7：发送请求 送信
			se.call(soapAction, envelope);
			// 步骤8：获取从互联网返回的结果，测试信有没有送到
			if (envelope.getResponse() != null) {
				Object result = envelope.getResponse();
				return result;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Retrieve data using get method.
	 */
	public static HttpEntity doGet(String url, HttpClient client, HttpHost host) {

		try {
			HttpGet httpRequest = new HttpGet(url);
			HttpResponse response = null;
			if (host == null) {
				response = client.execute(httpRequest);
			} else {
				response = client.execute(host, httpRequest);
			}
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {

				return null;
			}

			return response.getEntity();

		} catch (Exception e) {

			return null;
		} finally {
			try {
				client.getConnectionManager().closeIdleConnections(1000,
						TimeUnit.MILLISECONDS);
			} catch (Exception e) {

			}
		}
	}

	/**
	 * Retrieve data using get method.
	 */
	public static String doGet0(String url, HttpClient client, HttpHost host)
			throws Exception {
		BufferedReader in = null;

		HttpGet httpRequest = new HttpGet(url);
		HttpResponse response = null;
		try {
			if (host == null) {
				response = client.execute(httpRequest);
			} else {
				response = client.execute(host, httpRequest);
			}
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {

				return null;
			}

			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();

			return sb.toString();
			// return response.getEntity();

			// } catch (Exception e) {
			// Log.i(TAG, "Exception -- " + e.getMessage());
			// return null;
		} finally {
			try {
				client.getConnectionManager().closeIdleConnections(1000,
						TimeUnit.MILLISECONDS);
			} catch (Exception e) {
			}
			if (!httpRequest.isAborted()) {
				httpRequest.abort();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
		}
	}

	/**
	 * Get a http client object.
	 */
	public static synchronized HttpClient getHttpClient() {

		if (null == customerHttpClient) {
			HttpParams params = new BasicHttpParams();
			// Set basic parameters
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			/*
			 * HttpProtocolParams.setUserAgent(params,
			 * "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
			 * +
			 * "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1"
			 * );
			 */

			ConnManagerParams.setMaxTotalConnections(params, 100);
			ConnManagerParams.setTimeout(params, 10000);
			HttpConnectionParams.setConnectionTimeout(params, 300000);
			HttpConnectionParams.setSoTimeout(params, 60000);

			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 30010));
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);

			customerHttpClient = new DefaultHttpClient(conMgr, params);
		}

		return customerHttpClient;
	}

}
